package kr.co.graviti.common.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class JSONClient {
	
	private static JSONClient instance;
	
	public static synchronized JSONClient getInstance() {
		if (instance == null) {
			instance = new JSONClient();
		}
		
		return instance;
	}	
	
	public String request(String xmlFile2Send, String URL) throws IOException {

		// Create the connection where we're going to send the file.   
		URL url = new URL(URL);   
		URLConnection connection = url.openConnection();   
		HttpURLConnection httpConn = (HttpURLConnection) connection;   
		
		// Open the input file. After we copy it to a byte array, we can see   
		// how big it is so that we can set the HTTP Cotent-Length   
		// property. (See complete e-mail below for more on this.)   
		
		//FileInputStream fin = new FileInputStream(xmlFile2Send);
		InputStream is = new ByteArrayInputStream(xmlFile2Send.getBytes("UTF-8"));
		
		ByteArrayOutputStream bout = new ByteArrayOutputStream();       
		
		// Copy the SOAP file to the open connection.   
		copy(is, bout);   
		is.close();   
		
		byte[] b = bout.toByteArray();   
		
		// Set the appropriate HTTP parameters.   
		httpConn.setRequestProperty("Content-Length", String.valueOf( b.length ));   
		httpConn.setRequestProperty("Content-Type","text/json; charset=utf-8");   
		//httpConn.setRequestProperty("SOAPAction",SOAP_ACTION);   
		httpConn.setRequestMethod("GET");   
		httpConn.setDoOutput(true);
		httpConn.setDoInput(true);
		
		// Everything's set up; send the XML that was read in to b.   
		OutputStream out = httpConn.getOutputStream();   
		out.write( b );
		out.close();
		
		// Read the response and write it to standard out.   
		
		InputStreamReader isr =   
		new InputStreamReader(httpConn.getInputStream());   
		BufferedReader in = new BufferedReader(isr);   
		
		String inputLine;
		String str = "";
		
		while ((inputLine = in.readLine()) != null) {
//			System.out.println(inputLine);
//			str += in.readLine();
			str = inputLine;
		}

		in.close();
		
		return str;
	}	
	
	// copy method from From E.R. Harold's book "Java I/O"   
	public static void copy(InputStream in, OutputStream out) throws IOException {   

		// do not allow other threads to read from the   
		// input or write to the output while copying is   
		// taking place   

		synchronized (in) { 
			synchronized (out) {   

				byte[] buffer = new byte[256];   
				while (true) {   
					int bytesRead = in.read(buffer);   
					if (bytesRead == -1) break;   
						out.write(buffer, 0, bytesRead);  
				}   
			}   
		}   
	}
}
